//
//  QRCodeLoginViewController.m
//  WeChatRedBag
//
//  Created by srulos on 16/3/7.
//  Copyright © 2016年 srulos. All rights reserved.
//

#import "QRCodeLoginViewController.h"
#import "WeChatQQStaticLibHeader.h"

@interface QRCodeLoginViewController ()<UIScrollViewDelegate>
{
    NSString * m_uuid;
    BOOL m_isQuite;
    UIColor * m_color;
    NSTimer * m_timer;
    NSMutableArray * m_arrayTipsString;
}
@end

@implementation QRCodeLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"微信登陆";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(backBtnAction)];
    m_isQuite = NO;
    
//    [self.m_btnSaveAndJump setBackgroundColor:m_color];
    
    m_arrayTipsString = [[NSMutableArray alloc]init];
    [m_arrayTipsString addObject:@"点按钮跳转到微信扫一扫界面"];
    [m_arrayTipsString addObject:@"1.点击右上角相册"];
    [m_arrayTipsString addObject:@"2.从相册选择下载好的二维码"];
    [m_arrayTipsString addObject:@"3.点击右上角完成"];
    [m_arrayTipsString addObject:@"4.点击登录，并返回当前App"];
    
    CREATE_BORDER_EXTEND(self.m_btnSaveAndJump, 5, 1, 26, 174, 24, 1);
    
    UINavigationBar *bar = [UINavigationBar appearance];
    bar.barTintColor = m_color;
    bar.tintColor = [UIColor whiteColor];
    [bar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    
    [self loadQRCode];
}

- (void)backBtnAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    m_isQuite = YES;
}

- (IBAction)onSaveQRCodeJump2WeChat:(id)sender {
    UIImage * image = self.m_imgQrcode.image;
    if (image) {
        [self saveImageToPhotos:image];
    }
}

- (void)loadQRCode
{
    NSLog(@"二维码加载中...");
    [[AsyncWeChatSimulationService stander]asyncGetUUIDAndQRCode:^(NSString *uuid, NSData *data) {
        m_uuid = uuid;
        
        if (data != nil) {
            UIImage * qrcode = [UIImage imageWithData:data];
            [self.m_imgQrcode setImage:qrcode];

            [self checkQRCode];
            
            NSLog(@"加载二维码成功！");
            
            [self setScrollView];
        }
        else{
            NSLog(@"加载二维码失败！");
        }
    }];
}

-(void)checkQRCode
{
    if (m_isQuite) {
        return;
    }

    [[AsyncWeChatSimulationService stander]asyncCheckQRCode:m_uuid loginSuccessBlock:^{
        NSLog(@"登录成功！");
        [self dismissViewControllerAnimated:YES completion:nil];
    } setAvatarImage:^(UIImage *headImage) {
        if (headImage != nil) {
            self.m_btnSaveAndJump.hidden = YES;
            self.m_imgQrcode.hidden = YES;
            self.m_scrollView_scan_QRCode.hidden = YES;
            self.m_label_tips.hidden = YES;
            self.m_pageControl.hidden = YES;
            self.m_label_tips3.hidden = YES;
            
            self.m_labelTips2.hidden = NO;
            self.m_imgAvatar.hidden = NO;
            
            [self.m_imgAvatar setImage:headImage];
        }
        [self checkQRCode];
    } continueBlock:^{
        [self checkQRCode];
        NSLog(@"请扫描!!!");
    }];
}

- (void)saveImageToPhotos:(UIImage*)savedImage
{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存失败!";
        NSLog(@"%@",msg);
        return;
    } else {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]]){
            NSURL * url = [[NSURL alloc]initWithString:@"weixin://scanqrcode/"];
            [[UIApplication sharedApplication ]openURL:url];
        }
        else if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"wechat://"]]){
            NSURL * url = [[NSURL alloc]initWithString:@"weixin://scanqrcode/"];
            [[UIApplication sharedApplication ]openURL:url];
        }
        else{
            NSLog(@"保存成功!但本机没有安装微信!");
        }
    }
}

- (void)updateSaveBtnColor:(UIColor *)color{
    m_color = color;
}

- (void)setScrollView
{
    _m_scrollView_scan_QRCode.delegate = self;
    
    CGRect rect = _m_scrollView_scan_QRCode.frame;
    rect.size.width *= 5;
    _m_scrollView_scan_QRCode.contentSize = rect.size;
    
    self.m_pageControl.currentPage = 0;
    
    CGFloat imageW = _m_scrollView_scan_QRCode.frame.size.width;
    CGFloat imageH = imageW;
    
    for (int index = 1; index < 4; index++) {
        CGFloat imageX = index * imageW;
        UIImageView *imageView = [[UIImageView alloc] init];
        
        imageView.frame = CGRectMake(imageX, 0, imageW, imageH);
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"scan_help_%d.png", index]];
        [self.m_scrollView_scan_QRCode addSubview:imageView];
    }
    
    CGFloat imageX = 4 * imageW;
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(imageX, 0, imageW, imageH);
    imageView.image = [UIImage imageNamed:@"scan_help_wechat.png"];
    [self.m_scrollView_scan_QRCode addSubview:imageView];
    
    [self startTimer];
}

- (void)startTimer
{
    m_timer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:m_timer forMode:NSDefaultRunLoopMode];
}

- (void)updateTimer
{
    self.m_pageControl.currentPage = (self.m_pageControl.currentPage + 1) % 5;
    _m_label_tips3.text = [m_arrayTipsString objectAtIndex:self.m_pageControl.currentPage];
    
    [self pageChanged:self.m_pageControl];
}

- (void)pageChanged:(UIPageControl *)page
{
    CGFloat x = page.currentPage * self.m_scrollView_scan_QRCode.bounds.size.width;
    [self.m_scrollView_scan_QRCode setContentOffset:CGPointMake(x, 0) animated:YES];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 根据contentOffset计算页数
    int page = scrollView.contentOffset.x / scrollView.bounds.size.width;
    self.m_pageControl.currentPage = page;
    
    _m_label_tips3.text = [m_arrayTipsString objectAtIndex:self.m_pageControl.currentPage];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (m_timer) return;
    self.m_pageControl.currentPage = (scrollView.contentOffset.x + scrollView.frame.size.width * 0.5) / scrollView.frame.size.width;
    
    _m_label_tips3.text = [m_arrayTipsString objectAtIndex:self.m_pageControl.currentPage];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [m_timer invalidate];
    m_timer = nil;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self startTimer];
}

@end
